
import MpRequest from '../lib/mprequest.min';
import env from './env';
import ServiceError from './error';

const mprequest = new MpRequest({
  baseUrl: `${env.baseUrl}${env.gateway}`,
});

// 添加请求拦截器
mprequest.interceptors.request.use(function (options) {
  // 在发送请求之前做些什么
  return options;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
mprequest.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  const status = response.statusCode;
  if (status === 200) {
    const result = response.data;
    if (result.code === 200) {
      return result.data;
    } else {
      const timeout = setTimeout(() => {
        clearTimeout(timeout);
        wx.showToast({
          title: result.message,
          icon: 'none',
          duration: 2000,
        });
      }, 0);
      return Promise.reject(new ServiceError(JSON.stringify(result)));
    }
  } else if (status === 500) {
    const result = {
      code: 500,
      message: '服务器异常, 请稍后重试',
    };
    const timeout = setTimeout(() => {
      clearTimeout(timeout);
      wx.showToast({
        title: '服务器异常, 请稍后重试',
        icon: 'none',
        duration: 2000,
      });
    }, 0);
    return Promise.reject(new ServiceError(JSON.stringify(result)));
  }
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default mprequest;
